import { Dimensions, Platform, PixelRatio, StatusBar } from 'react-native';
import { initialWindowMetrics } from 'react-native-safe-area-context';

export const { height, width } = Dimensions.get('window');

export const topInset: any = initialWindowMetrics?.insets.top || 40;

// 真实高度
export const HEIGHT = { current: 0 };

//UI设计图的宽高
const designWidth = 750;
const designHeight = 1334;

let defaultPixel = 2;

let wd = designWidth / defaultPixel;
let hd = designHeight / defaultPixel;
//获取缩放比例
let _scale = Math.min(width / wd, height / hd);
let fontScale = PixelRatio.getFontScale();

// export const scale = (size: number): number => {
//     size = (size * _scale * fontScale) / defaultPixel;
//     return (size as any).toFixed(2) - 0;
// };

export const scale = (size: number): number => {
    size = (size * _scale) / defaultPixel; // 不使用 fontScale
    return parseFloat(size.toFixed(2));
};

export const px2dp = (px: number): number => {
    px = (px * width) / 750;
    return (px as any).toFixed(2) - 0;
};

export const isIos = () => Platform.OS === 'ios';

// iPhoneX  & XS
const X_WIDTH = 375;
const X_HEIGHT = 812;

// iPhoneXR & XsMax
const XR_WIDTH = 414;
const XR_HEIGHT = 896;

function isIPhoneX() {
    return isIos() && ((height === X_HEIGHT && width === X_WIDTH) || (height === X_WIDTH && width === X_HEIGHT));
}

//判断是否为IPhoneXR或XsMAX
function isIPhoneXR() {
    return isIos() && ((height === XR_HEIGHT && width === XR_WIDTH) || (height === XR_WIDTH && width === XR_HEIGHT));
}

const iosHeight = isIPhoneX() || isIPhoneXR() ? 44 : 20;

export const statusBarHeight: any = isIos() ? iosHeight : StatusBar.currentHeight;

export const onePx = 1 / PixelRatio.get();

//iPhoneX R 底部高度兼容处理
export function isIPhoneXFooter(number = 0) {
    return number + (isIPhoneX() || isIPhoneXR() ? 34 : 0);
}

// 没有底部导航的 页面高度
export const bodyHeight = height - statusBarHeight - px2dp(88);
// 底部导航的高度
export const tabHeight = px2dp(98);

// 同一时间内 执行最后一次 防抖 执行最后一次：
export const debounce = (func: Function, time = 1000) => {
    let timer: any;
    return (...args: any) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            //以集合形式传递参数，用apply
            func.apply(this, args);
        }, time);
    };
};

export const throttle = (fn: Function, wait = 1000) => {
    let lastTime: any = false;
    return (...arg: any) => {
        let nowTime = new Date().getTime();
        if (nowTime - lastTime > wait || !lastTime) {
            fn(...arg);
            lastTime = nowTime;
        }
    };
};

// 检测版本号
export const compareVersions = (v1, v2) => {
    const arr1 = v1.split('.').map(Number);
    const arr2 = v2.split('.').map(Number);

    for (let i = 0; i < Math.max(arr1.length, arr2.length); i++) {
        const num1 = arr1[i] || 0; // 如果版本号长度不一致，补 0
        const num2 = arr2[i] || 0;
        if (num1 > num2) return 1; // v1 > v2
        if (num1 < num2) return -1; // v1 < v2
    }
    return 0; // 相等
}